package com.eonmind.pay.service.impl;

import com.eonmind.common.contract.timer.Timer;
import com.eonmind.common.provider.entity.pay.Order;
import com.eonmind.common.provider.entity.pay.PaymentInfo;
import com.eonmind.pay.entity.WxChatPay;
import com.eonmind.pay.enums.PayWayType;
import com.eonmind.pay.enums.TradeState;
import com.eonmind.pay.mapper.PaymentInfoMapper;
import com.eonmind.pay.service.OrderService;
import com.eonmind.pay.service.PaymentInfoService;
import com.google.gson.Gson;
import com.mongoplus.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName PaymentInfoServiceImp
 * @Description TODO
 * Author 32004
 * Date 2025/5/31 14:39
 * Version 1.0
 **/


@Slf4j
@Service
public class PaymentInfoServiceImp extends ServiceImpl<PaymentInfo> implements PaymentInfoService {

    @Resource
    private PaymentInfoMapper paymentInfoMapper;

    @Resource
    private OrderService orderService;

    @Resource
    WxChatPay wxChatPay;


    @Override
    public void createPaymentInfo(String plainText) {

        log.info("记录支付日志");

        Gson gson = new Gson();
        HashMap plainMap = gson.fromJson(plainText, HashMap.class);

        //订单号
        String orderNo = (String) plainMap.get("out_trade_no");
        //业务编号(微信的唯一支付业务编号)
        String transactionId = (String) plainMap.get("transaction_id");
        //支付类型
        String tradeType= (String) plainMap.get("trade_type");
        //交易状态
        String tradeState = (String) plainMap.get("trade_state");
        //net st
        Map<String,Object> amount= (Map<String, Object>) plainMap.get("amount");
        Integer payerTotal=0;
        if(amount.get("payer_total") == null) {

            try {
                wxChatPay.closeOrder(orderNo);
                orderService.updateOrderStatusAndPayTime(Long.parseLong(orderNo), TradeState.CLOSED.getCode(), Timer.currentTimestamp());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            return;
        }else {
            payerTotal= ((Double) amount.get("payer_total")).intValue();

        }
        //支付金额(单位分)


        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setOrderNo(orderNo);
        paymentInfo.setPaymentType(PayWayType.WEIXIN.getCode());
        paymentInfo.setTransactionId(transactionId);
        paymentInfo.setTradeType(tradeType);
        paymentInfo.setTradeState(tradeState);
        paymentInfo.setPayerTotal(payerTotal);
        paymentInfo.setContent(plainText);

        this.save(paymentInfo);
    }



}
